package com.imm.da.main.launch

import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.util.Log
import androidx.activity.result.ActivityResult
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.imm.da.R
import com.imm.da.base.vm.BaseVMActivity
import com.imm.da.databinding.ActivityApplaunchBinding

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 启动页
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2024/3/21
 */
class AppLaunchActivity: BaseVMActivity<AppLaunchViewModel, ActivityApplaunchBinding>(R.layout.activity_applaunch) {

    private val location: LocationClient by lazy {
        LocationClient.setAgreePrivacy(true)
        LocationClient(this, initLocationOption())
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        Log.v("aaaaa", "result:$result")
    }

    override fun initActivity() {

        // 指纹识别界面
//        val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager ?: return
//        if (keyguardManager.isKeyguardSecure){
//            Log.v("aaaaa", "000")
//            keyguardManager.createConfirmDeviceCredentialIntent("aa", "bb")?.let {
//                registerActivityResult(it)
//            }
//        }else {
//            Log.v("aaaaa", "设备不支持指纹")
//        }




        BiometricManager.from(this@AppLaunchActivity).canAuthenticate(
            BiometricManager.Authenticators.BIOMETRIC_STRONG).let {
                when(it){
                    BiometricManager.BIOMETRIC_SUCCESS -> {
                        Log.e("aaaaa", "用户可以进行身份验证")
                    }
                    BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> {
                        Log.e("aaaaa", "无法确定用户是否可以进行身份验证")
                    }
                    BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> {
                        Log.e("aaaaa", "Android版本较低，不支持身份验证")
                    }
                    BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
                        Log.e("aaaaa", "用户未添加身份认证凭证，不支持身份验证")
                    }
                    BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
                        Log.e("aaaaa", "设备硬件限制，不支持身份验证")
                    }
                    else -> {
                        Log.e("aaaaa", "设备不支持生物身份认证, error code:$it")
                    }
                }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
            BiometricPrompt(this@AppLaunchActivity, ContextCompat.getMainExecutor(this),
                object : BiometricPrompt.AuthenticationCallback() {
                    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                        super.onAuthenticationSucceeded(result)
                        Log.v("aaaaa", "----------- onAuthenticationSucceeded ---------cipher:${result.cryptoObject?.cipher}")
                    }

                    override fun onAuthenticationFailed() {
                        super.onAuthenticationFailed()
                        Log.v("aaaaa", "----------- onAuthenticationFailed ---------")
                    }

                    override fun onAuthenticationError(
                        errorCode: Int,
                        errString: CharSequence
                    ) {
                        super.onAuthenticationError(errorCode, errString)
                        Log.v("aaaaa", "----------- onAuthenticationError ---------errorCode:$errorCode; errString:$errString")
                    }
                })
                .authenticate(
                    BiometricPrompt.PromptInfo.Builder()
                        // Authenticators.BIOMETRIC_STRONG 人脸指纹虹膜 强度3
                        // Authenticators.BIOMETRIC_WEAK 人脸指纹虹膜 强度2
                        // Authenticators.DEVICE_CREDENTIAL 密码验证
                        .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.BIOMETRIC_STRONG)
                        // 是否允许设备凭证
                        .setDeviceCredentialAllowed(false)
                        .setConfirmationRequired(true)
                        .setTitle("setTitle")
                        .setSubtitle("setSubtitle")
                        .setDescription("setDescription")
                        .setNegativeButtonText("setNegativeButtonText")
                        .build()
                    )
        }else {
            val fingerprintManager = getSystemService(Context.FINGERPRINT_SERVICE) as? FingerprintManager ?: return
            if (fingerprintManager.isHardwareDetected){
                Log.v("aaaaa", "设备支持指纹识别")
                if (fingerprintManager.hasEnrolledFingerprints()){
                    Log.v("aaaaa", "设备已经录入指纹")
                }else {
                    Log.v("aaaaa", "设备尚未录入指纹")
                }
            }else {
                Log.v("aaaaa", "设备不支持指纹识别")
            }

            fingerprintManager.authenticate(null, null, 0, object : FingerprintManager.AuthenticationCallback() {
                override fun onAuthenticationFailed() {
                    super.onAuthenticationFailed()
                    Log.v("aaaaa", "指纹认证失败")
                }

                override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult?) {
                    super.onAuthenticationSucceeded(result)
                    Log.v("aaaaa", "指纹认证成功")
                }

                override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
                    super.onAuthenticationError(errorCode, errString)
                    Log.v("aaaaa", "指纹认证异常, errorCode:$errorCode")
                }

                override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence?) {
                    super.onAuthenticationHelp(helpCode, helpString)
                    Log.v("aaaaa", "指纹不匹配, helpString:$helpString")
                }

            }, null)
        }



//        location.registerLocationListener(object : BDAbstractLocationListener() {
//            override fun onReceiveLocation(location: BDLocation?) {
//                location?.city?.let { viewModel.query(ImgParam(q = it)){ url ->
//                    LogHelper.e("image url:$url")
//                    ImgLoader.load(binding.launchBg, url, skipMemory = true)
//                } }?: LogHelper.e("location error")
//            }
//        })
    }

    /**
     * 配置定位属性
     */
    private fun initLocationOption(): LocationClientOption{
        return LocationClientOption().apply {
            // 首次定位，速度优先
            setFirstLocType(LocationClientOption.FirstLocType.SPEED_IN_FIRST_LOC)
            // 高精度定位模式
            locationMode = LocationClientOption.LocationMode.Hight_Accuracy
            // 默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
            setCoorType("gcj02")
            // 默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
            setScanSpan(0)
            // 设置是否需要地址信息，默认不需要
            setIsNeedAddress(true)
            // 设置是否需要设备方向结果
            setNeedDeviceDirect(true)
            // 默认false，设置是否当卫星定位有效时按照1S 1次频率输出卫星定位结果
            setOnceLocation(false)
            // 默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
            setIgnoreKillProcess(true)
            // 默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
            setIsNeedLocationDescribe(true)
            // 默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
            setIsNeedLocationPoiList(false)
            // 默认false，设置是否收集CRASH信息，默认收集
            isIgnoreCacheException = false
            // 默认false，设置是否开启卫星定位
            isOpenGnss = true
            // 默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
            setIsNeedAltitude(true)
            // 设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
            // setOpenAutoNotifyMode()
            // 设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
            // setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT)

        }
    }

    override fun onResume() {
        super.onResume()
        location.start()
    }

    override fun onPause() {
        super.onPause()
        location.stop()
//        finish()
    }

}